﻿using Microsoft.Practices.Composite.Events;
using Microsoft.Practices.Composite.Presentation.Events;
using StockholmsStad.Windows.UI.Infrastructure.Events;
using StockholmsStad.Windows.UI.Interfaces;

namespace StockholmsStad.Windows.UI
{
    /// <summary>
    /// Interaction logic for Shell.xaml
    /// </summary>
    public partial class Shell : IShell
    {
        private readonly IEventAggregator eventAggregator;
        private SubscriptionToken subscriptionToken;

        public Shell(IEventAggregator aggregator)
        {
            eventAggregator = aggregator;
            InitializeComponent();

            Loaded += Shell_Loaded;
         }

        private void Shell_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            var changedTitleEvent = eventAggregator.GetEvent<UIEvent>();

            if (subscriptionToken != null)
                changedTitleEvent.Unsubscribe(subscriptionToken);

            subscriptionToken = changedTitleEvent.Subscribe(UIEventHandler, ThreadOption.UIThread, false);

            eventAggregator.GetEvent<UIEvent>().Subscribe(UIEventHandler);
        }

        private void UIEventHandler(UIEventArgs e)
        {
            Model.ShellTitle = e.ShellTitle;
        }

        #region IShellView Members

        public void ShowView()
        {
            Show();
        }

        public IShellPresentationModel Model
        {
            get { return DataContext as IShellPresentationModel; }
            set { DataContext = value; }
        }

        #endregion
    }
}
